#include "memPool_t.h"

int memPool_t::_defaultPageSize = 31;

memPool_t::memPool_t(int numOfPages) : _pages(numOfPages)
{
	for (int i = 0; i < numOfPages ; i++)
		_pages[i] = new memPage_t(_defaultPageSize);

	_numOfPages = numOfPages;
	_usedSpace = 0;
	_current = 0;
	_capacity = numOfPages * _defaultPageSize;
}

memPool_t::~memPool_t()
{
	vector<memPage_t*>::iterator iter = _pages.begin();	
	while (iter != _pages.end())
	{
		delete *iter;
		iter++;
	}
}

bool memPool_t::isEmpty()
{
	return _usedSpace == 0;
}

int memPool_t::getPosition()
{
	return _current;
}

bool memPool_t::setPosition(int position) 
{
	int differnce = position - _current;
	int sizeOfPagesBeforeCurrentPage =  0;
	
	if (position <= _usedSpace) 
	{	
		int positionInPage = 0;
		_current = position;
		memPage_t* currntPage = CurrentPageAndPosition(positionInPage);
		getCurrentMemoryPage()->setPosition(positionInPage);
	}
	else 
	{
		return false;
	}
}


int memPool_t::getUsedSpace()
{
	return _usedSpace;
}
int memPool_t::getCapacity()
{
	return _capacity;
}
int memPool_t::getNumOfPages()
{
	return _numOfPages;
}

memPage_t* memPool_t::getFirstMemoryPage()
{
	return _pages.front();
}
memPage_t* memPool_t::getLastMemoryPage()
{
	
	return _pages.back();

}
memPage_t* memPool_t::getCurrentMemoryPage()
{
	int placeInPage = 0;
  	return CurrentPageAndPosition(placeInPage);
}

memPage_t* memPool_t::CurrentPageAndPosition(int& placeInPage)
{
	vector<memPage_t*>::iterator iter = _pages.begin();	
	int temp = _current;
	int numOfBytesInPreviousPages = 0;
	
	while( (*iter != _pages.back()) && (temp > (*iter)->getCapacity() - 1) )
	{
		temp -= (*iter)->getActualSize();
		numOfBytesInPreviousPages += (*iter)->getCapacity();
		iter++;
	}

	placeInPage = _current - numOfBytesInPreviousPages;
	return *iter;
}


void memPool_t::addMemoryPages(int count)
{
	_pages.resize(getNumOfPages() + count);
	_capacity += count*_defaultPageSize;
	
	for (int i =0; i < count; i++)
		_pages[i + getNumOfPages()] = new memPage_t(_defaultPageSize);

	_numOfPages += count;
	
}

int memPool_t::getDefaultPageSize()
{
	return _defaultPageSize;
}

void memPool_t::setDefaultPageSize(int size)
{
	_defaultPageSize = size;
}
